#include "threads.h"

int elog_thrd_finger()
{
	#ifndef NO_THREADS
	return 1;
	#else
	return 0;
	#endif
}

void __launch_func(struct elog_thread *th)
{
  th->state = ELOG_THRD_STATE_BUSY;

  th->func(th->thread_data);
  
  th->state = ELOG_THRD_STATE_DONE;
  pthread_exit(NULL);
}


void __launch_func0(struct elog_thread *th)
{
	th->state = ELOG_THRD_STATE_BUSY;

	th->func0();

	th->state = ELOG_THRD_STATE_DONE;
	pthread_exit(NULL);
}

void elog_thrd_finish(struct elog_thread *th, int patience)
{
  while (th->state > 0)
    usleep(patience);
}

struct elog_thread *elog_thrd_launch(void *(* func)(void*), void *func_data)
{
  struct elog_thread *th = elog_thr_thread_new();
  th->thread_data = func_data;
  th->func = func;
  pthread_create(&(th->sysThread), NULL, __launch_func, th);
  //__launch_func(th);
  return th;
}
struct elog_thread *elog_thrd_launch0(void *(* func)(void))
{
	struct elog_thread *th = elog_thr_thread_new();
	th->thread_data = NULL;
	th->func0 = func;
	pthread_create(&(th->sysThread), NULL, __launch_func0, th);
	//__launch_func(th);
	return th;
}

struct elog_thread* elog_thr_thread_new()
{
  return malloc(sizeof(struct elog_thread));
}
void elog_thr_thread_free(struct elog_thread *th)
{
  if (th)
    {
      if (th->thread_data)
	free(th->thread_data);
      free(th);
    }
}
void elog_thrd_exit(struct elog_thread *th)
{
	printf("Thread Exit\n");
	pthread_cancel(th->sysThread);
}
